package com.zzf.concurrent.example.design.pattern.balking;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author GaoFeng2017
 * @date 2019/9/8 19:17
 */
public class Data {
    private volatile String filename;
    private volatile String content;
    private volatile boolean isChanged;

    public Data() {

    }

    /**
     * 主动修改文件
     * @author ZengZhengFang
     * @date 2019/9/8 19:23
     * @param filename 文件名
     * @param content 文件内容
     * @return void
     */
    public synchronized void change(String filename, String content) {
        this.filename = filename;
        this.content = content;
        this.isChanged = true;
    }

    /**
     * 将最新的内容保存文件
     * @author ZengZhengFang
     * @date 2019/9/8 19:24
     */
    public synchronized boolean save() {

        if (!isChanged) {
            // 文件没被修改多则不保存
            return false;
        }
        doSave();
        isChanged = false;

        return true;
    }

    private void doSave() {
        try (FileOutputStream out = new FileOutputStream(filename)) {
            out.write(content.getBytes());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
